<template>
  <div>
    <basic-container-one>
      <vue-element-loading :active="isActive" spinner="bar-fade-scale" color="#409eff" background-color="rgba(255,255,255,0.2)"/>
      <el-form :inline="true" :model="formInline" >
        <div style="margin-top: 22px">
          <!--<el-form-item>
            <el-input clearable v-model="formInline.gameName" placeholder="游戏名称"/>
          </el-form-item>-->
          <el-form-item>
            <el-select v-model="formInline.gameName" filterable clearable placeholder="游戏名称">
              <el-option
                v-for="item in gamelist"
                :key="item.gameName"
                :label="item.gameName"
                :value="item.gameName"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select v-model="formInline.platformName" filterable clearable placeholder="平台">
              <el-option
                v-for="item in platformNameList" v-show="item.length>0"
                :key="item"
                :label="item"
                :value="item"/>
            </el-select>
          </el-form-item>


          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="queryFunc">查询</el-button>
            <el-button icon="el-icon" type="primary" @click="addExeclProfitSet">批量导入配置信息</el-button>
            <el-button icon="el-icon" type="primary" @click="exportExeclProfitSet">导出配置信息</el-button>
          </el-form-item>
        </div>
      </el-form>
    </basic-container-one>
    <basic-container>
      <div style="margin-top: 20px">
        <el-table
          :data="dailyStatisticsList"
          stripe
          ref="el-table"
          style="width: 100%">
          <el-table-column
            prop="gameName"
            label="游戏名称"
            min-width="20%">
          </el-table-column>
          <el-table-column
            prop="platformName"
            label="平台"
            min-width="10%">
          </el-table-column>

          <el-table-column
            prop="profitSc"
            label="首充比例"
            min-width="20%">
          </el-table-column>
          <el-table-column
            prop="profitXc"
            label="续充比例"
            min-width="20%">
          </el-table-column>
<!--          <el-table-column
            prop="profitBd"
            label="首充补点"
            min-width="20%">
          </el-table-column>-->
          <el-table-column label="操作" min-width="10%">
            <template slot-scope="scope">
              <el-button @click="editGame(scope.row)"  type="text" size="medium">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="block" style="margin-top: 20px;">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.current"
          :page-sizes="[10, 20, 50, 100, 200]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </div>

    </basic-container>

    <el-dialog :title="mode" :visible.sync="dialogEditFormVisible" @close="closeEditDialog()" :close-on-click-modal="false" customClass="customView2">
      <div v-if="dialogEditFormVisible">
        <el-form :model="editForm" :rules="rules" label-width="130px" class="demo-ruleForm" ref="ruleForm">
          <el-form-item label="游戏名称：" prop="gameName">
            <el-input v-model="editForm.gameName" clearable placeholder="请输入游戏名称" maxlength='100' style="width:350px" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="平台：">
            <el-input v-model="editForm.platformName" clearable placeholder="请输入平台" maxlength='100' style="width:350px" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="首充比例：">
            <el-input v-model="editForm.profitSc" clearable placeholder="请输入首充比例" maxlength='100' style="width:350px"></el-input>
          </el-form-item>
          <el-form-item label="续充比例：">
            <el-input v-model="editForm.profitXc" clearable placeholder="请输入续充比例" maxlength='100' style="width:350px"></el-input>
          </el-form-item>
          <el-form-item label="扩展配置：">
<!--            <el-input v-model="editForm.profitBd" clearable placeholder="请输入首充补点" maxlength='100' style="width:350px"></el-input>-->
            <el-select v-model="editForm.ruleType" clearable placeholder="扩展配置">
              <el-option :value="0" label="不配置"/>
              <el-option :value="1" label="按时间范围配置"/>
            </el-select>
          </el-form-item>
          <el-row v-if="gRuleType === 1" v-for="(itemList,index) in editForm.timeGameProfitconfigList" :key="index">
            <el-col span="6">
              <el-form-item label="首充比例:">
                <el-input v-model="itemList.profitSc" clearable placeholder="请输入首充比率" maxlength='100' style="min-width: 100px;" ></el-input>
              </el-form-item>
            </el-col>
            <el-col span="6">
              <el-form-item label="续充比例:">
                <el-input v-model="itemList.profitXc" clearable placeholder="请输入续充比率" maxlength='100' ></el-input>
              </el-form-item>
            </el-col>
            <el-col span="10">
              <el-form-item  label="时间段:" style="margin-bottom: 0px">
                <el-date-picker
                  type="datetimerange"
                  v-model="itemList.selTime"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col span="2" style="padding-left: 15px;">
              <el-button type="success" v-if="index==0" @click="addTakeEffectInput" icon="el-icon-plus"></el-button>
              <el-button type="danger" v-if="index>0" @click="delTakeEffectInput(index)" icon="el-icon-minus"></el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeEditDialog()">取 消</el-button>
        <el-button type="primary" @click="saveEditGame()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="mode" :visible.sync="dialogPlFormVisible" @close="closePlDialog()" :close-on-click-modal="false" customClass="customWidthCompany">
      <div v-if="dialogPlFormVisible" style="text-align: center">
        <el-form :inline="true" :model="formGrant" label-width="170px" class="demo-form-inline" ref="grantForm" style="margin-top: 25px">
          <el-row>
            <el-col>
              <el-form-item prop="excelPath" label="补单信息文件：">
                <el-upload
                  style="width: 350px;text-align: left"
                  :action="''"
                  list-type="text"
                  :on-remove="isiconRemove"
                  :before-upload="beforeAvatarUpload"
                  :file-list="excelUrlList"
                  :limit="1"
                  :http-request="uploadicon">
                  <span class="font-14">选择文件</span>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closePlDialog" style="width: 150px">取 消</el-button>
        <el-button v-loading.fullscreen.lock="fullscreenLoading" type="primary" @click="suerPl()" style="width: 150px">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from "vuex";

import {
  getTimeConfigList, loadSpendQrSerach,
  queryGamesQr,
  queryPageSpendQrGamesProfit,
  saveExeclGamesProfitSet,
  saveSpendQrGamesProfit
} from "@/api/system/details";
import moment from "moment";
import {getToken} from '@/util/auth';
import {cloneObj} from '@/util/util'
import VueElementLoading from 'vue-element-loading'
import {upLoad} from "@/api/base/oss";
import {dateFormat} from "@/util/date";

export default {
  name: "day",
  data() {
    return {
      fullscreenLoading: false,
      formGrant: {
        excelPath:'',
      },
      excelUrlList:[],
      dialogPlFormVisible:false,
      isActive: false,
      gamelist:[],
      dialogEditFormVisible:false,
      platformNameList:[],
      formInline: {
        gameName: '',
        platformName: '',
      },
      page: {
        current: 1,
        size: 10,
        total: 0,
      },
      dailyStatisticsList: [],
      checked: false,
      isshowtrue: false,
      ischange: true,
      showRuleForm: false,
      editForm:{
        gameName:'',
        ruleType:0,
        configId:null,
        platformName:'',
        profitSc:'',
        profitXc:'',
        profitBd:'',
        /*timeGameProfitconfigList:[{
          startTime: dateFormat(new Date()),
          endTime: dateFormat(new Date()),
          profitSc:0,
          profitXc:0,
          selTime:[],
        }],*/
        timeGameProfitconfigList:[{
          startTime: null,
          endTime: null,
          profitSc:null,
          profitXc:null,
          selTime:[],
        }],
      },
      rules: {
        gameName:[
          {required: true, message: '请输入游戏归类名称', trigger: 'blur'}
        ],
      }
    }

  },
  components: {
    VueElementLoading
  },
  computed: {
    ...mapGetters(["userInfo"]),
    gRuleType(){
      return this.editForm.ruleType
    }
  },
  mounted() {
    this.loadGames()
    this.refreshTable()
  },


  methods: {
    addTakeEffectInput() {
      this.editForm.timeGameProfitconfigList.push({'id': '', 'profitSc': '', 'profitXc':'', 'selTime':'' })
    },
    delTakeEffectInput(index) {
      // console.log(index)
      this.editForm.timeGameProfitconfigList.splice(index, 1)
    },
    closePlDialog() {
      this.dialogPlFormVisible = false
      this.formGrant = {
        excelPath:''
      }
    },
    addExeclProfitSet(){
      this.dialogPlFormVisible = true;
      this.mode = '批量导入补单信息';
    },
    exportExeclProfitSet(){
      window.open(`/api/blade-details/spend/export-pageGameProfitconfig?blade-auth=${getToken()}`);
    },
    uploadicon(params) {
      this.selectExcel(params)
    },
    async selectExcel(params) {
      let file = params.file
      let url = ''
      // console.log(file.name)
      await upLoad("excel", file.name).then(res => {
        url = res.data;
      })
      this.upLoadscuess(url, file);
    },
    upLoadscuess(url, file) {
      axios.put(url, file, {headers: {"Content-Type": "application/octet-stream"},withCredentials: false,}).then(res => {
        // console.log("上传成功", res)
        if (res.status === 200) {
          // this.isicon = true
          this.formGrant.excelPath = res.request.responseURL.split("?")[0]
        }
      })
    },
    isiconRemove: function () {
      this.formGrant.excelPath = ''
    },
    beforeAvatarUpload(file) {
      let isLt2M = file.size / 1024 / 1024 < 4;
      const imgType = file.type === 'application/vnd.ms-excel'
      if (!imgType) {
        this.$message({
          type: "warning",
          message: "请先选择的格式为.xls的excel文件!"
        });
        return false;
      }
      if (!isLt2M) {
        this.$message({
          type: "warning",
          message: "请先选择的excel不要大于4M!"
        });
        return false;
      }
      return true
    },

    suerPl() {
      if (this.formGrant.excelPath == '') {
        this.$message({
          type: "error",
          message: '请选择要导入的文件！'
        });
        return;
      }
      this.fullscreenLoading = true

      saveExeclGamesProfitSet(this.formGrant).then(res => {
        this.fullscreenLoading=false
        this.dialogPlFormVisible=false
        this.formGrant = {
          excelPath:'',
        }
        if (res.data.success) {
          this.$alert(res.data.msg, '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.refreshTable()
            }
          });
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
      })
    },
    validateReBuild(){
      // console.log('this.editForm.ruleType ===1',this.editForm.ruleType ===1)
      if(this.editForm.ruleType ===1){
        // 要进行验证
        let list = this.editForm.timeGameProfitconfigList
        if (list === null || list.length === 0) {
          this.$message({
            type: "warning",
            message: '至少添加一条规则'
          });
          return false
        }
        let line = 0
        for(let item of list){
          line++;
          if (item.selTime && item.selTime.length === 2) {
            item.startTime = (item.selTime[0])
            item.endTime = (item.selTime[1])
          }else{
            this.$message({
              type: "warning",
              message: '第'+line+'条，时间范围不能为空'
            });
            return false
          }
          if (!item.profitSc) {
            this.$message({
              type: "warning",
              message: '第'+line+'条，首充比率不能为空'
            });
            return false
          }
          if (!item.profitXc) {
            this.$message({
              type: "warning",
              message: '第'+line+'条，续充比率不能为空'
            });
            return false
          }
        }
      }
      return true
    },
    saveEditGame(){
      // console.log('this.editForm',this.editForm)
      if(!this.validateReBuild()){
        return
      }
      saveSpendQrGamesProfit(this.editForm).then(res => {
        if (res.data.success) {
          this.$message({
            type: "success",
            message: "更新成功!"
          });
          this.closeEditDialog()
          this.refreshTable();
        } else {
          this.$message({
            type: "error",
            message: res.data.msg
          });
        }
      });
    },

    editGame(row){
      this.dialogEditFormVisible = true
      this.mode = '编辑游戏利润比例';
      this.editForm.profitSc = row.profitSc
      this.editForm.profitXc = row.profitXc
      this.editForm.profitBd = row.profitBd
      this.editForm.gameName = row.gameName
      this.editForm.platformName = row.platformName
      this.editForm.ruleType = row.ruleType === -1 ?0:row.ruleType
      let obj = {}
      obj.configId = row.configId
      getTimeConfigList(obj).then((res)=>{
        // console.log('edit----',res)
        if (res.status === 200) {
          let list = res.data.data
          if (list && list.length > 0) {
            for (let item of list) {
              item.selTime = [item.startTime,item.endTime]
            }
            this.$set(this.editForm,'timeGameProfitconfigList',res.data.data);
          }

        }
      })
    },
    closeEditDialog(){
      this.dialogEditFormVisible = false
      this.editForm = {
        profitSc:'',
        profitXc:'',
        profitBd:'',
        gameName:'',
        platformName:'',
        ruleType:0,
        timeGameProfitconfigList:[{
          startTime: null,
          endTime: null,
          profitSc:null,
          profitXc:null,
          selTime:[],
        }],
      }
    },

    changeLine(str){
      return str.replaceAll(',','&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
    },

    loadGames() {
      queryGamesQr().then(res => {
        this.gamelist = res.data.data
      })

      loadSpendQrSerach().then(res => {
        this.platformNameList = res.data.data.platformName
      })
    },

    /**
     * 搜索按钮
     */
    queryFunc() {
      this.page.current = 1
      this.refreshTable()
    },

    refreshTable() {
      this.isActive = true
      this.getPageSpendQrGamesProfit()
    },

    getPageSpendQrGamesProfit() {
      let formData = cloneObj(this.formInline);
      queryPageSpendQrGamesProfit(formData, this.page.current, this.page.size).then(res => {
        this.isActive = false
        let data = res.data.data
        this.dailyStatisticsList = data.records
        this.page.total = data.total
      })
    },
    handleSizeChange(val) {
      this.page.size = val
      this.refreshTable()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.refreshTable()
    },

  }
}
</script>

<style lang="scss">
.customView2{
  width: 70%;
  background-color: #FFFFFF !important;
}
</style>
